package server

import (
	"Redbook/redbook/internal/Domain"
	"Redbook/redbook/internal/reposetery"
	"context"
)

type ArticleService interface {
	Save(ctx context.Context, articl Domain.Articl) (int, error)
	Publish(ctx context.Context, articl Domain.Articl) error
}

type articleService struct {
	crepo reposetery.ArticleRepo
	brepo reposetery.ArticleRepo
}

func NewArticleService(crepo reposetery.ArticleRepo, brepo reposetery.ArticleRepo) ArticleService {
	return &articleService{
		crepo: crepo, //客户端
		brepo: brepo, //工作端
	}
}

func (a *articleService) Save(ctx context.Context, articl Domain.Articl) (int, error) {
	if articl.ID != 0 {
		return articl.ID, a.crepo.Update(ctx, articl)
	}
	return a.crepo.Creat(ctx, articl)
}

// 发布库
func (a *articleService) Publish(ctx context.Context, articl Domain.Articl) error { //发布
	id, err := a.Save(ctx, articl) //保存
	if err != nil {
		return err
	}
	articl.ID = id
	err = a.brepo.Save(ctx, articl)
	return err
}
